package org.easyx.ser.sys.serivce.impl;

import java.util.ArrayList;
import java.util.List;

import org.easyx.ser.sys.entity.SysUser;
import org.easyx.ser.sys.entity.SysUserRole;
import org.easyx.ser.sys.mapper.SysUserMapper;
import org.easyx.ser.sys.serivce.SysUserRoleService;
import org.easyx.ser.sys.serivce.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author xiaojl
 * @since 2017-09-11
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

	@Autowired
	private SysUserRoleService userRoleService;
	
	@Override
	public void insertWithCascade(SysUser entity, String roleIds) {
		this.insert(entity);
		Long userId = entity.getId();
		
		String[] roles = roleIds.split(",");
		if(userId!=null && roles!=null && roles.length>0){
			List<SysUserRole> urList = new ArrayList<SysUserRole>();
			for(String s : roles){
				SysUserRole ur = new SysUserRole();
				ur.setRoleId(Long.parseLong(s));
				ur.setUserId(userId);
				ur.setCreateBy(entity.getCreateBy());
				urList.add(ur);
			}
			userRoleService.insertBatch(urList);
		}
		
	}

	@Override
	public void updateWithCascade(SysUser entity, String roleIds) {
		this.updateById(entity);
		Long userId = entity.getId();
		userRoleService.delete(new EntityWrapper<SysUserRole>().eq("userId",userId));
		
		String[] roles = roleIds.split(",");
		if(userId!=null && roles!=null && roles.length>0){
			List<SysUserRole> urList = new ArrayList<SysUserRole>();
			for(String s : roles){
				SysUserRole ur = new SysUserRole();
				ur.setRoleId(Long.parseLong(s));
				ur.setUserId(userId);
				ur.setCreateBy(entity.getCreateBy());
				urList.add(ur);
			}
			userRoleService.insertBatch(urList);
		}
	}

	@Override
	public void deleteWithCascade(SysUser entity) {
		Long userId = entity.getId();
		userRoleService.delete(new EntityWrapper<SysUserRole>().eq("userId",userId));
		
		this.deleteById(userId);
	}

}
